package com.example.stray_animal_management_system.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.stray_animal_management_system.commonu.service.RescueInfoService;
import com.example.stray_animal_management_system.entity.RescueInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @description:
 * @author: panpan
 * @time: 2025/11/1
 */
@RestController
@RequestMapping("/api/admin/rescue")
public class RescueInfoAdminController {

    @Autowired
    private RescueInfoService rescueInfoService;

    /**
     * 查询救助上报记录（分页 + 条件）
     */
    @GetMapping("/list")
    public Map<String, Object> list(
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "animalType", required = false) String animalType,
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "size", defaultValue = "10") int size
    ) {
        Page<RescueInfo> p = new Page<>(page, size);
        LambdaQueryWrapper<RescueInfo> query = new LambdaQueryWrapper<>();

        if (status != null) query.eq(RescueInfo::getStatus, status);
        if (animalType != null && !animalType.isEmpty()) query.like(RescueInfo::getAnimalType, animalType);

        IPage<RescueInfo> result = rescueInfoService.page(p, query.orderByDesc(RescueInfo::getReportTime));

        Map<String, Object> res = new HashMap<>();
        res.put("code", 200);
        res.put("data", result.getRecords());
        res.put("total", result.getTotal());
        return res;
    }

    /**
     * 添加救助记录（管理员手动添加）
     */
    @PostMapping("/add")
    public Map<String, Object> add(@RequestBody RescueInfo info) {
        info.setReportTime(LocalDateTime.now());
        info.setRescueCode("R" + System.currentTimeMillis());
        rescueInfoService.save(info);

        Map<String, Object> res = new HashMap<>();
        res.put("code", 200);
        res.put("msg", "添加成功");
        return res;
    }

    /**
     * 更新救助记录
     */
    @PutMapping("/update")
    public Map<String, Object> update(@RequestBody RescueInfo info) {
        rescueInfoService.updateById(info);
        Map<String, Object> res = new HashMap<>();
        res.put("code", 200);
        res.put("msg", "更新成功");
        return res;
    }

    /**
     * 删除救助记录（支持批量）
     */
    @DeleteMapping("/delete")
    public Map<String, Object> delete(@RequestParam("ids") List<Integer> ids) {
        rescueInfoService.removeByIds(ids);
        Map<String, Object> res = new HashMap<>();
        res.put("code", 200);
        res.put("msg", "删除成功");
        return res;
    }

    /**
     * 上传救助图片
     */
    @PostMapping("/upload")
    public Map<String, Object> uploadPhoto(@RequestParam("file") MultipartFile file) {
        Map<String, Object> res = new HashMap<>();
        if (file.isEmpty()) {
            res.put("code", 400);
            res.put("msg", "文件为空");
            return res;
        }

        String uploadDir = System.getProperty("user.dir") + "/uploads/rescue_photos/";
        File dir = new File(uploadDir);
        if (!dir.exists()) dir.mkdirs();

        String fileName = UUID.randomUUID() + "_" + file.getOriginalFilename();
        File dest = new File(uploadDir + fileName);

        try {
            file.transferTo(dest);
            String fileUrl = "http://localhost:8080/uploads/rescue_photos/" + fileName;
            res.put("code", 200);
            res.put("msg", "上传成功");
            res.put("url", fileUrl);
        } catch (IOException e) {
            res.put("code", 500);
            res.put("msg", "上传失败：" + e.getMessage());
        }

        return res;
    }
    /**
     * 管理员审批通过接口
     */
    @PostMapping("/approve")
    public Map<String, Object> approve(@RequestParam("id") Integer id) {
        Map<String, Object> res = new HashMap<>();

        RescueInfo info = rescueInfoService.getById(id);
        if (info == null) {
            res.put("code", 404);
            res.put("msg", "记录不存在");
            return res;
        }

        info.setStatus(1); // 状态改为 1（进行中）
        rescueInfoService.updateById(info);

        res.put("code", 200);
        res.put("msg", "审核通过");
        return res;
    }

    /**
     * 驳回救助请求
     */
    @PostMapping("/reject")
    public Map<String, Object> reject(@RequestParam("id") Integer id,
                                      @RequestParam("reason") String reason) {
        Map<String, Object> res = new HashMap<>();

        RescueInfo info = rescueInfoService.getById(id);
        if (info == null) {
            res.put("code", 404);
            res.put("msg", "记录不存在");
            return res;
        }

        info.setStatus(3); // 状态设为“驳回”
        info.setRejectReason(reason);
        rescueInfoService.updateById(info);

        res.put("code", 200);
        res.put("msg", "已驳回");
        return res;
    }


}
